package org.vincen.helloworld.coding;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSA {

	public static void main(String[] args) {
		
		byte[] plainText = null;
		try {
			plainText = "Our business is life itself".getBytes("UTF8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		//构成一个RSA密钥
		System.out.println("\nStart generating RSA key");
		KeyPairGenerator keyGen = null;
		try {
			keyGen = KeyPairGenerator.getInstance("RSA");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		keyGen.initialize(1024);
		KeyPair key=keyGen.generateKeyPair();
		System.out.println("Finish generating RSA key");
		
		PrivateKey privateKey = key.getPrivate();
		System.out.println("Print private key : ");
		System.out.println(privateKey.toString());
		
		PublicKey publicKey = key.getPublic();
		System.out.println("Print public key : ");
		System.out.println(publicKey.toString());
		
		//获得一个RSA的Cipher类，使用公共密钥加密
		Cipher cipher = null;
		try {
			cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
			e.printStackTrace();
		}
		System.out.println("\n"+cipher.getProvider().getInfo());

		System.out.println("\nStart encryption");
		byte[] cipherText = null;
		String transText = null;
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key.getPublic());
			cipherText = cipher.doFinal(plainText);
			System.out.println("Finish encryption:");
			System.out.println(new String(cipherText,"UTF8"));
			transText = BaseConversion.btyes2HexStr(cipherText);
			System.out.println("print transfer coding");
			System.out.println(transText);
		} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		//使用私有密钥解密
		System.out.println("\nStart decryption");
		byte[] codeText = BaseConversion.hexStr2Bytes(transText);
		try {
			cipher.init(Cipher.DECRYPT_MODE,key.getPrivate());
			byte[] newPlainText=cipher.doFinal(codeText);
			System.out.println("Finish decryption:");
			System.out.println(new String(newPlainText,"UTF8"));
		} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}
}
